package cn.wit.summit.chwan.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameDailyNewAdapter;
import cn.wit.summit.chwan.adapters.PrizesGameListAdapter;
import cn.wit.summit.chwan.interfaces.AdapterInterface;
import cn.wit.summit.chwan.interfaces.MyScrollListener;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.DailyNewRequest;
import cn.wit.summit.chwan.models.response.GameDailyNewResponse;
import cn.wit.summit.chwan.models.response.PrizesGameListResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * 每日上新
 * Created by Alan on 2018/4/17.
 */

public class PrizesGameListActivity extends BaseActivity implements AdapterInterface {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private int pn = 1;
    private int pc = 20;
    private PrizesGameListAdapter mPrizesGameListAdapter;

    private List<PrizesGameListAdapter.ViewBean> viewBeans = new ArrayList<>();

    private LinearLayoutManager layoutManager;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private String prize_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prizes_game_list);
        ButterKnife.bind(this);

        prize_id = getIntent().getStringExtra("prize_id");

        if (retrofitManager==null) {
            retrofitManager = RetrofitManager.getInstance(mContext);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }

        initList();
    }

    @Override
    public void reGetData() {
        super.reGetData();
        viewBeans.clear();
        mPrizesGameListAdapter.notifyDataSetChanged();
        pn = 1;
        getDailyNewData();
        refreshLayout.autoRefresh();
    }

    private void initList() {
        mPrizesGameListAdapter = new PrizesGameListAdapter(this, viewBeans, this);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mPrizesGameListAdapter);
        recyclerView.setFocusable(false);
        recyclerView.addOnScrollListener(new MyScrollListener());
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getDailyNewData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getDailyNewData();
            }
        });

        showSkeleton();
        pn = 1;
        getDailyNewData();
    }

    private void getDailyNewData() {
        api.getPrizesGameList(retrofitManager.prizesGameListRequest(prize_id, pn, pc)).enqueue(new MyCallback<ResponseBase<PrizesGameListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<PrizesGameListResponse> model) {
                hideSkeleton();
                updataUi(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                hideSkeleton();
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
                refreshLayout.finishRefresh();
                showToast(msg);
            }
        });
    }

    private void updataUi(PrizesGameListResponse data) {

        if (data == null) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        if (pn == 1) {
            setBarTitleTx(data.getSub_title());
            mPrizesGameListAdapter.clearTempData();
            viewBeans.clear();
        }

        if (!StringUtils.isEmpty(data.getPic()) && pn == 1) {
            PrizesGameListAdapter.ViewBean viewBean = new PrizesGameListAdapter.ViewBean(PrizesGameListAdapter.ViewType.TYPE_IMAGE, data.getPic());
            viewBeans.add(viewBean);
        }

        List<GameDailyNewResponse.GameListBean> dataList = data.getGame_list();
        if (dataList == null || dataList.size() == 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        for (int i = 0; i < dataList.size(); i++) {
            GameDailyNewResponse.GameListBean temp = dataList.get(i);
            PrizesGameListAdapter.ViewBean view = new PrizesGameListAdapter.ViewBean(PrizesGameListAdapter.ViewType.TYPE_LIST, temp);
            viewBeans.add(view);
        }

        if (dataList.size() <= 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        } else {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            pn++;
        }

        mPrizesGameListAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = mPrizesGameListAdapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = mPrizesGameListAdapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }
        super.onEventMainThread(downloadEvent);
    }

    @Override
    public void onAdapterItemClick(View view, int position) {
        switch (view.getId()) {
            case R.id.itemDailyNewIv:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (viewBeans != null && viewBeans.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_daily_new_skeleton;
    }
}
